package com.dek.grpc.header;

import com.dek.grpc.dto.HelloReply;
import com.dek.grpc.dto.HelloRequest;
import com.dek.grpc.service.HelloServiceGrpc;
import com.dek.grpc.service.IHelloService;
import io.grpc.*;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CustomHeaderClient {

    private static final Logger logger = Logger.getLogger(CustomHeaderClient.class.getName());

    private final ManagedChannel originChannel;
    private final HelloServiceGrpc.HelloServiceBlockingStub blockingStub;

    /**
     * A custom client.
     */
    private CustomHeaderClient(String host, int port) {
        originChannel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build();
        ClientInterceptor interceptor = new HeaderClientInterceptor();
        Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
        blockingStub = HelloServiceGrpc.newBlockingStub(channel);
    }

    private void shutdown() throws InterruptedException {
        originChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    private void sayHello(String name) {
        logger.info("Will try to sayHello " + name + " ...");
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
            return;
        }
        logger.info("sayHello: " + response.getMessage());
    }

    /**
     * Main start the client from the command line.
     */
    public static void main(String[] args) throws Exception {
        CustomHeaderClient client = new CustomHeaderClient("localhost", 50051);
        try {
            client.sayHello("world");
        } finally {
            client.shutdown();
        }
    }


}
